﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BuildManager.Site.App_Start
{
	public class ModelBindingConfig
	{
		public static void RegisterModelBindings(ModelBinderDictionary binders)
		{
			binders[typeof(DateTime)] = new DateTimeModelBinder();
			binders[typeof(DateTime?)] = new DateTimeModelBinder();
		}
	}

	public class DateTimeModelBinder : IModelBinder
	{
		object IModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			try
			{

				ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

				var s = value.AttemptedValue;
				if (!string.IsNullOrEmpty(s))
				{
					if (!s.Contains("Date("))
					{
						DateTime dt;
						if (DateTime.TryParse(s, out dt))
							return dt;
					}
					s = s.Replace("/", "");
					s = s.Replace(")", "");
					s = s.Replace("Date(", "");
					long ticks = 0;
					if (long.TryParse(s, out ticks))
					{
						var dt = new DateTime(1970, 1, 1).AddMilliseconds(ticks);
						return dt;
					}
				}
			}
			catch (Exception x)
			{
				var m = x.Message;
			}
			return DateTime.MinValue;
		}		
	}
}